package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.activity.SplashActivity;
import com.linjian.togetherbirthday.base.BaseFragment;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.sdsmdg.tastytoast.TastyToast;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class NickUserPicFragment extends BaseFragment implements View.OnClickListener {

    private SplashActivity activity;

    private View mView;
    private ImageView userPicIv;
    private Button bt_go;
    private EditText etNickName;

    private String upImgUri;

    private ArrayList<AlbumFile> mAlbumFiles;

    public static NickUserPicFragment newInstance(String info){
        NickUserPicFragment nickUserPicFragment = new NickUserPicFragment();
        Bundle bundle = new Bundle();
        bundle.putString("info",info);
        nickUserPicFragment.setArguments(bundle);
        return nickUserPicFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int setView() {
        return R.layout.fragmnet_user_pic;
    }

    @Override
    protected void init(View view) {
        mView = view;
        activity = (SplashActivity)getActivity();

        userPicIv = view.findViewById(R.id.user_pic_iv);
        bt_go = view.findViewById(R.id.bt_go_user_pic);
        etNickName = view.findViewById(R.id.et_user_nick);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        setListener();
    }
    private void setListener() {
        userPicIv.setOnClickListener(this);
        bt_go.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.user_pic_iv:
                selectAlbum();
                break;
            case R.id.bt_go_user_pic:
                if (TextUtils.isEmpty(etNickName.getText())){
                    TastyToast.makeText(getActivity(), "必须要填写昵称", TastyToast.LENGTH_SHORT,TastyToast.WARNING).show();
                }else if (upImgUri == null){
                    TastyToast.makeText(getActivity(), "必须上传头像", TastyToast.LENGTH_SHORT,TastyToast.WARNING).show();
                }else {
                    httpUpUserInfo(upImgUri,etNickName.getText().toString());
                }

                break;
        }
    }

    /**
     * Select picture, from album.
     */
    private void selectAlbum() {
        Album.album(this)
                .multipleChoice()
                .columnCount(2)
                .selectCount(1)
                .camera(true)
                .cameraVideoQuality(1)
                .cameraVideoLimitDuration(Integer.MAX_VALUE)
                .cameraVideoLimitBytes(Integer.MAX_VALUE)
                .checkedList(mAlbumFiles)
                .widget(
                        Widget.newDarkBuilder(getActivity())
                                .title("图片选择")
                                .build()
                )
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
                        mAlbumFiles = result;
//                        mAdapter.notifyDataSetChanged(mAlbumFiles);
//                        mTvMessage.setVisibility(result.size() > 0 ? View.VISIBLE : View.GONE);
                        if (result.get(0).getMediaType() == AlbumFile.TYPE_IMAGE){
                            upImg(result.get(0).getPath(),result.get(0).getBucketName());
                        }else {
                            TastyToast.makeText(getActivity(), "不能选用视频作为头像哦", TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                        }

                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        TastyToast.makeText(getActivity(), "已取消", TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                })
                .start();
    }

    /**
     * 上传图片
     */
    private void upImg(String imgUrl,String fileName){
        HttpUtils.doFile(HttpContant.URL + HttpContant.UpImgUri+"1"
                ,"SESSION="+String.valueOf(SharedPreferencesUtil.get(getActivity(),"Cookie",""))
                , imgUrl
                , fileName
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("upImg",response.body().string()));
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event){
        switch (event.getCls()){
            case "requestFail":
                TastyToast.makeText(getActivity(), "请求失败", TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                break;
            case "upImg":
                Log.i("NickUserPic",event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        Glide.with(getActivity()).load(object.getString("data")).error(R.mipmap.user_pic).placeholder(R.mipmap.user_pic)
                                .crossFade().into(userPicIv);
                        upImgUri = object.getString("data");
                    }else {
                        TastyToast.makeText(getActivity(), object.getString("msg"), TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case "setUserInfo":
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        Map<String,Object> map = new Gson().fromJson(getArguments().getString("info"),Map.class);
                        map.put("nickname",etNickName.getText().toString());
                        map.put("headImg",upImgUri);
                        SharedPreferencesUtil.put(getActivity(),"LoginInfo",new Gson().toJson(map));
                        activity.startActivity("PersonalCenterFragment");
                        String account = String.valueOf(SharedPreferencesUtil.get(getActivity(),"LoginPhone",""));
                        String name = etNickName.getText().toString();
                        activity.login(account,name);
                    }else {
                        TastyToast.makeText(getActivity(), object.getString("msg"), TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    /**
     * 上传用户信息
     */
    private void httpUpUserInfo(String imgUrl,String nickName){
        Map<String,Object> map = new Gson().fromJson(getArguments().getString("info"),Map.class);
        map.put("nickname",nickName);
        map.put("headImg",imgUrl);
        HttpUtils.Put(HttpContant.URL + HttpContant.OneLoginUpInfo
                ,"SESSION="+String.valueOf(SharedPreferencesUtil.get(getActivity(),"Cookie",""))
                , "type"
                , "2"
                , map
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("setUserInfo",response.body().string()));
                    }
                });
    }
}
